<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\wxapp\controller;

use api\wxapp\controller\ApiBaseController;
use think\Db;
use api\wxapp\model\Order;
use api\wxapp\model\Shop;
use api\wxapp\model\OrderList;
use api\wxapp\model\User;
use api\wxapp\model\Score;
use api\wxapp\model\Config;
use api\wxapp\model\Integral;
use api\wxapp\model\Balance;
class WxPayController extends ApiBaseController
{
    public function index()
    {
        $params = $this->getParam();
        !isset($params['ordernum']) ? $this->error('参数缺失!!!') : '';
        //判断  余额支付  微信支付 积分支付  还是什么支付
        $ordernum = $params['ordernum'];
        $find = Order::where('ordernum',$ordernum)->find();
        if($find['score'] > 0){ //说明有积分
            if($find['pay_price'] > 0){ //说明是积分  微信混合支付
                $this->pay($find);
            }else{
                $this->scorePay($find);
            }
        }else{//微信支付
            $this->pay($find);
        }
    }
    public function pay($info)
    {
        require_once "./WxPay/lib/WxPay.Api.php";
        require_once "./WxPay/example/WxPay.JsApiPay.php";
        require_once './WxPay/example/log.php';
        $config = new \WxPayConfig();
        //记录日志
        //file_put_contents('./public/pay_logs/false_'.date('Y-m-d',time()).'.txt',$k.'--'.$v.PHP_EOL,FILE_APPEND);
        $this->error('213',$config);
        $openId = User::where('id',$info['uid'])->value('openid');

        $order = $info['ordernum'];//这里我写的是订单号
        $money = $info['pay_price'] * 100;

        //初始化值对象
        $input = new \WxPayUnifiedOrder();
        //文档提及的参数规范：商家名称-销售商品类目
        $input->SetBody("商家名称");
        //订单号应该是由小程序端传给服务端的，在用户下单时即生成，demo中取值是一个生成的时间戳
        $input->SetOut_trade_no("$order");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //费用应该是由小程序端传给服务端的，在用户下单时告知服务端应付金额，
        $input->SetTotal_fee("$money");
        $input->SetNotify_url("回调地址自己写！！！");
        $input->SetTrade_type("JSAPI");
        //由小程序端传给服务端
        $input->SetOpenid($openId);//APPID小程序传过来 或者数据库读取。
        //向微信统一下单，并返回order，它是一个array数组
        $order = \WxPayApi::unifiedOrder($config, $input);

        if ($order['return_code'] == 'SUCCESS') {
            $info = array(
                'appId' => $order['appid'],
                'timeStamp' => "" . time() . "",
                'nonceStr' => $order['nonce_str'],
                'package' => 'prepay_id=' . $order['prepay_id'],
                'signType' => 'MD5',
            );
            $info['paySign'] = $this->sign($info);//验签！！关键！！！！！！
            // json化返回给小程序端
            // header("Content-Type: application/json");
            return json($info);
        } else {
            return json(['msg' => 'fail']);
        }
    }

    //验签方法
    public function sign($data, $key = '这里是支付APIKEY，必填！！！')
    {
        ksort($data);
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        $string = $buff . "&key=" . $key;
        $string = md5($string);
        $sign = strtoupper($string);
        return $sign;
    }

    //支付成功  回调
    /******
     * 1:修改订单状态
     * 2.赠送积分
     * 3.计算收益返利
     * 4.是否使用优惠券  更改优惠券状态
     */
    public function payNotify()
    {
        $params = $this->getParam();
        $ordernum = $params['ordernum'];
        $info = Order::where('ordernum',$ordernum)->find();
        //执行 支付成功后的操作
        //记录日志
        //file_put_contents('./public/pay_logs/false_'.date('Y-m-d',time()).'.txt',$k.'--'.$v.PHP_EOL,FILE_APPEND);
        Db::startTrans();
        try{
            $data['pay_time'] = $this->returnDateTime();
            $data['status'] = 2;//代发货状态
            $res = Order::where('id',$info['id'])->update($data);
            if(!$res){
                throw new \Exception('订单跟新失败!!');
            }
            //计算赠送积分 只计算商品价格  不计算  算运费
            $sbl = Config::where('id',13)->value('value');
            $score = $info['goods_price'] * $sbl;
            $data1['uid'] = $info['uid'];
            $data1['integral'] = round($score);
            $data1['addtime'] = $this->returnDateTime();
            $data1['type'] = 1;
            $data1['remark'] = '消费获得积分';
            $data1['status'] = 1;
            $data1['time'] = $this->returnDate();
            $res1 = Integral::insert($data1);
            if(!$res1){
                throw new \Exception('积分记录添加失败!!');
            }
            //用户积分添加
            $res2 = User::where('id',$info['uid'])->setInc('integral',$data1['integral']);
            if(!$res2){
                throw new \Exception('用户积分更新失败!!');
            }
            //判断当前用户是否有  推荐店员
            $user = User::get($info['uid']);
            if($user['puid']){
                $bbl = Config::where('id',14)->value('value');
                $balance = round($info['goods_price']/$bbl,2);
                //添加余额记录
                $data3['uid'] = $user['puid'];
                $data3['balance'] = $balance;
                $data3['type'] = 1;
                $data3['remark'] = '推荐会员消费返利';
                $data3['addtime'] = $this->returnDateTime();
                $data3['orderid'] = $info['id'];
                $res3 = Balance::insert($data3);
                if(!$res3){
                    throw new \Exception('推荐店员余额记录添加失败!!');
                }
                //更新店员的余额
                $res4 = User::where('id',$user['puid'])->setInc('balance',$balance);
                if(!$res4){
                    throw new \Exception('店员余额更新失败!!');
                }
            }
            //判断   当前订单的商品 有没有  平台售卖的   在进行返利   查看是否使用了优惠券
            $idarr = OrderList::where(['order_id'=>$info['id'],'goods_id'=>0])->select();
            if($idarr){
                //此订单存在直邮商品
                $money = 0;
                foreach($idarr as $k=>$v){
                    $money += $v['price']*$v['num'];
                }
                //添加余额 店铺
                $pbl = Config::where('id',15)->value('value');
                $pbalance = round($money/$pbl,2);
                //添加余额记录
                $data4['shop_id'] = $params['shop_id'];
                $data4['balance'] = $pbalance;
                $data4['type'] = 1;
                $data4['remark'] = '店铺售卖平台商品,店铺返利';
                $data4['addtime'] = $this->returnDateTime();
                $data4['orderid'] = $info['id'];
                $res5 = Balance::insert($data4);
                if(!$res5){
                    throw new \Exception('店铺返利记录添加失败!!');
                }
                //更新店铺的余额
                $res6 = Shop::where('id',$params['shop_id'])->setInc('balance',$balance);
                if(!$res6){
                    throw new \Exception('店铺余额添加失败!!');
                }
            }
            //在判断当前订单是否使用了优惠券
            if($info['is_coupon']){
                $res7 = db::name('app_coupon_list')->where(['uid'=>$info['uid'],'coupon_id'=>$info['is_coupon']])->update(['type'=>2]);
                if(!$res7){
                    throw new \Exception('优惠券状态更新失败!!');
                }
            }
            Db::commit(); 
        }catch(\Exception $e){
            Db::rollback(); //回滚事务
            $this->error($e->getMessage());
        }
        $this->success('处理成功!',true);
    }
    //积分支付 处理
    public function scorePay($find)
    {
        if($find['score'] > User::where('id',$find['uid'])->value('integral')){
            $this->error('当前积分小于支付需要支付的积分');
        }
        //单纯积分
        Db::startTrans();
        try{
            //
            $data['uid'] = $find['uid'];
            $data['integral'] = $find['score'];
            $data['type'] = 1;
            $data['status'] = 2;//减少
            $data['time'] = date('Y-m-d',time());
            $data['addtime'] = date('Y-m-d H:i:s',time());
            $data['remark'] = '积分兑换扣除积分';
            $res = Score::insert($data);
            if(!$res){
                throw new \Exception('订单表储存失败');
            }
            //减少用户积分
            $res1 = User::where('id',$find['uid'])->setDec('integral',$find['score']);
            if(!$res1){
                throw new \Exception('用户积分更新失败');
            }
            //更新订单状态
            $res2 = Order::where('id',$find['id'])->update(['status'=>2,'pay_time'=>date('Y-m-d H:i:s',time())]);
            if(!$res2){
                throw new \Exception('订单状态更新失败');
            }
            Db::commit(); 
        }catch(\Exception $e){
            Db::rollback(); //回滚事务
            $this->error($e->getMessage());
        }
        $this->success('兑换成功!',$find);
    }
}
